/**
 * Copyright (C), 2017-2018, XXX有限公司
 * FileName: UnitPanel2
 * Author:   zengjian
 * Date:     2018/8/14 11:01
 * Description: 单元测试生成面板
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package org.yinxue.swing.unit.main;

import fun.codedesign.yinxue.util.LogUtil;
import fun.codedesign.yinxue.util.batch.FileCallback;
import org.yinxue.swing.core.panel.YxUnitPanel;
import org.yinxue.swing.core.standard.YxStructure;
import org.yinxue.swing.core.util.SwingUtils;
import fun.codedesign.yinxue.config.UserConfig;
import org.yinxue.swing.unit.context.Context;
import fun.codedesign.yinxue.util.batch.filter.JavaFilter;
import fun.codedesign.yinxue.util.batch.BatchFileUtil;
import org.yinxue.swing.unit.model.JavaFile;
import org.yinxue.swing.unit.util.UnitUtil;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;

import static javax.swing.WindowConstants.HIDE_ON_CLOSE;

/**
 * 〈单元测试生成面板〉<br>
 * 〈一句话描述〉
 *
 * @author zengjian
 * @create 2018/8/14 11:01
 */
public class UnitPanel2 extends YxUnitPanel implements YxStructure {

    public UnitPanel2() {
        super();
    }

    @Override
    public void action() {
        super.action();
        jText_inputpath.setText(UserConfig.getUserProjectPath());
        topInput.append(Context.config().defaultUnitCode);
        rightInfo.append("我是单元测试编写小助手，来试试我的[一键执行]吧！\n");

        jButton_generate.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (0 == jComboBox_operateType.getSelectedIndex()) {
                    try {
                        downOutput.setText(UnitUtil.getUnitContext(topInput.getText()));
                    } catch (Exception e1) {
                        LogUtil.error(this, "生成失败", e1);
                        rightInfo.append(e1.getClass() + ":" + e1.getMessage());
                    }
                } else if (1 == jComboBox_operateType.getSelectedIndex()) {
                    final String path = getAndSetInputPath();
                    threadPool().submitSingle(() -> {
                        long now = System.currentTimeMillis();
                        mailBox().sendMessage("批量读取java文件...");
                        BatchFileUtil.batchReadFileByThread(path, new JavaFilter(), path1 -> {
                            JavaFile file = new JavaFile(path1);
                            return null;
                        });
                        int count = UnitUtil.batchCreateUnitContextFile();
                        long now2 = System.currentTimeMillis();
                        long seconds = (now2 - now) / 1000;
                        mailBox().sendMessage("生成单元测试文件:" + count + "个，耗时:" + seconds + "秒,清单见:\"D:\\log\\list.txt\"!\n");
                    });
                } else if (2 == jComboBox_operateType.getSelectedIndex()) {
                    threadPool().submitSingle(new Runnable() {
                        @Override
                        public void run() {
                            mailBox().sendMessage("回滚开始...");
                            int count = BatchFileUtil.rollBack("E:\\log\\list.txt");
                            mailBox().sendMessage("回滚结束:" + count + "个文件已回滚!\n");
                        }
                    });
                } else {

                }
            }
        });

        jCheckBox_isPojo.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    Context.config().setPojo(true);
                } else if (e.getStateChange() == ItemEvent.DESELECTED) {
                    Context.config().setPojo(false);
                } else {
                    throw new RuntimeException("你到了不可到达的区域，很神奇！");
                }
            }
        });

        jButton_open.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                threadPool().submitSingle(new Runnable() {
                    String path = getAndSetInputPath();

                    @Override
                    public void run() {
                        long time = System.currentTimeMillis();
                        mailBox().sendMessage("容器开启...");
                        BatchFileUtil.batchReadFileByThread(path, new JavaFilter(), new FileCallback() {
                            @Override
                            public String callFile(File path) {
                                JavaFile javaFile = new JavaFile(path);
                                return null;
                            }
                        });
                        mailBox().sendMessage("容器开启完成，耗时:" + (System.currentTimeMillis() - time) + "ms");
                        mailBox().sendMessage("容器包含类解析实例：" + Context.register().classDescSize() + "个\n");
                    }
                });
            }
        });


        jComboBox_operateType.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                int chooseIndex = jComboBox_operateType.getSelectedIndex();
                // 先复位，避免勾选
                jCheckBox_isPojo.setSelected(false);
                if (chooseIndex == 0) {
                    jCheckBox_isPojo.setVisible(true);
                } else if (chooseIndex == 1 || chooseIndex == 2) {
                    jCheckBox_isPojo.setVisible(false); // 修改为隐藏
                } else {
                    // Dothing
                }
                // 将设置的状态置为false，避免批量生成时取值错误
                Context.config().setPojo(false);
            }
        });

        jButton_diy.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        ConfigFrame.singleton.setVisible(true);
                        ConfigFrame.singleton.setSpecClassDesc(Context.config().getSpecClassDesc());
                    }
                });
            }
        });
    }



    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
//                SwingUtils.initDefaultUI();
            JFrame jFrame = SwingUtils.ofJFrameWithMenuBar("yinxue-unit", 1600, 900, new UnitPanel2());
            jFrame.setIconImage(new ImageIcon("icon/app_icon.png").getImage());
            jFrame.setVisible(true);
        });
    }

    public static void run() {
        SwingUtilities.invokeLater(() -> {
//                SwingUtils.initDefaultUI();
            JFrame jFrame = SwingUtils.ofJFrameWithMenuBar("yinxue-unit", 1280, 800, new UnitPanel2());
            jFrame.setIconImage(new ImageIcon("icon/app_icon.png").getImage());
            jFrame.setDefaultCloseOperation(HIDE_ON_CLOSE);
            jFrame.setVisible(true);
        });
    }
}